import Taro, { Component } from "@tarojs/taro";
import { View, Text, Picker } from "@tarojs/components";
import { connect } from "@tarojs/redux";
import { $Req } from "@utils";
import { AtList, AtListItem, AtAvatar, AtIcon, AtButton } from "taro-ui";
import "./index.scss";

@connect(
  ({ userModel }) => ({
    userModel,
  }),
  (dispatch) => ({
    userAction: dispatch.userModel,
  })
)
export default class Index extends Component {
  config = {
    navigationBarTitleText: "个人信息",
  };

  constructor(props) {
    super(...arguments);

    this.state = {
      currentTab: 0,
      user: {}
    };
  }

  // 点击列表
  onListItemClick(type) {
    Taro.navigateTo({
      url: "/pages/user/info/edit?type=" + type,
    });
  }

  onDateChange(v) {}

  componentDidShow() {
    this.getUserInfo();
  }

  async getUserInfo() {
    let { code, data } = await $Req({
      type: "post",
      url: "/user/getUserCenterInfo",
      data: {},
    });
    
    if (code == 200) {
      this.setState({
        user: data
      })
    }
  }

  getUserInfos = ({ detail: { userInfo: { avatarUrl } } }) => this.updateAvatar(avatarUrl);

  async updateAvatar(avatarUrl) {

    console.log("从微信端获取的头像地址：" + avatarUrl);

    let { code, message, data } = await $Req({
      type: "post",
      url: "/user/updateUserWx",
      data: {
        userPhoto: avatarUrl,
      },
    });

    if (code !== 200) return;
    Taro.showToast({
      title: "更新成功"
    })

    this.state.user.userPhoto = avatarUrl;

    this.setState({
      user: this.state.user
    })
  }

  render() {
    const {
      userModel: { userInfo },
    } = this.props;

    let { user } = this.state;

    return (
      <View className="page-user-info">
        <View className="at-row at-row__justify--between at-row__align--center r1" id="getUserinfos">
          <View className="at-col at-col-2 c11">头像</View>
          <View className="at-col at-col-2 c12">
            <AtAvatar
              size="normal"
              circle
              image={user.userPhoto}
            ></AtAvatar>
            <AtButton openType="getUserInfo" onGetUserInfo={this.getUserInfos}>
              <AtIcon value='reload' size='20' color='#ccc'></AtIcon>
            </AtButton>
          </View>
        </View>
        <AtList>
          <AtListItem
            title="用户名"
            extraText={user.name}
            arrow="right"
            onClick={() => {
              this.onListItemClick(1);
            }}
          />
          <AtListItem
            title="年龄"
            extraText={user.age}
            arrow="right"
            onClick={() => {
              this.onListItemClick(0);
            }}
          />
          <AtListItem title="手机号" extraText={user.userPhone} />
        </AtList>
      </View>
    );
  }
}
